#include "stdafx.h"
#include "./rendermgr.h"

//ambien light
GLfloat ambientLight[] = { 0.5f, 0.5f, 0.5f, 1.0f};

RenderMgr::RenderMgr()
: m_bSkipOnce(true)
{
	m_thread.OnSetupRC += EventObject<OnRenderContextReadyFunc>(this, &RenderMgr::OnRenderContextReady);
	m_thread.OnRenderScene += EventObject<OnRenderSceneFunc>(this, &RenderMgr::OnRenderScene);
	m_thread.OnRenderChangeSize += EventObject<OnRenderSizeChangedFunc>(this, &RenderMgr::OnRenderChangeSize);

	m_lastTime.QuadPart = 0;
}

RenderMgr::~RenderMgr()
{

}

void RenderMgr::SkipOnce()
{
	m_bSkipOnce = true;
}

void RenderMgr::Start(HDC hDC)
{
	m_thread.Init(hDC);
	m_thread.Start();
}

void RenderMgr::Stop()
{
	m_thread.Stop();
}

void RenderMgr::SetWinSize(Size size)
{
	m_thread.SetWinSize(size);
}

/* call by render thread */
void RenderMgr::OnRenderContextReady()
{
	glShadeModel(GL_SMOOTH);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_COLOR_MATERIAL);
	//glEnable(GL_CULL_FACE);
	glFrontFace(GL_CCW);

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);

	glEnable(GL_COLOR_MATERIAL);
	
	glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

	FireEvent(OnRenderStartFunc, OnStart, ());
}

void RenderMgr::OnRenderScene()
{
	time_type curTime = TimeUtils::GetTime();	
	float differTime = TimeUtils::GetTimeDiffer(curTime, m_lastTime);
	m_lastTime = TimeUtils::GetTime();

	if (m_bSkipOnce)
	{
		m_bSkipOnce = false;
		return;
	}

	FireEvent(OnBeforeRenderFunc, OnBeforeRender, (differTime));

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glColor3ub(255, 255, 255);
	FireEvent(OnRenderFunc, OnRender, (differTime));

	FireEvent(OnAfterRenderFunc, OnAfterRender, (differTime));

	FireEvent(OnExtRenderFunc, OnExtRender, ());
}

void RenderMgr::OnRenderChangeSize(Size size)
{
	glViewport(0, 0, size.cx, size.cy);
}